<template>
  <!-- 配色 -->
  <a-form :label-col="labelCol" class="color-box">
    <a-button type="primary" @click="addColor">{{ t('添加') }}</a-button>
    <a-button
      v-if="data.info.config.colors.length > 0"
      type="primary"
      danger
      @click="deleteColor"
      class="ml-4"
      >{{ t('删除') }}</a-button
    >
    <template
      v-if="data.info.config && data.info.config.colors && Array.isArray(data.info.config.colors)"
    >
      <SelectColor
        class="mt-4"
        v-for="(_item, index) in data.info.config.colors"
        :key="index"
        v-model:value="data.info.config.colors[index]"
        @change="changeInfo"
      />
    </template>
  </a-form>
</template>

<script setup lang="ts">
  import { computed, reactive } from 'vue';
  import { EChartsOption } from 'echarts';
  import SelectColor from './../SelectColor.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const labelCol = { style: { width: '70px' } };
  const props = withDefaults(
    defineProps<{
      info: {
        config: {
          colors: Array<string>;
          echarts: EChartsOption;
        };
      };
    }>(),
    {
      info: () => {
        return {
          config: {
            colors: [],
            echarts: {
              alignTicks: true,
            },
          },
        };
      },
    },
  );
  const colorLength = computed(() => {
    return data.info.config.echarts.series && data.info.config.echarts.series[0].data
      ? data.info.config.echarts.series[0].data
      : 0;
  });
  const emit = defineEmits(['update:info', 'change']);
  const data = reactive({
    info: props.info,
  });
  function changeInfo() {
    initChartColors();
    emit('update:info', data.info);
    emit('change');
  }
  function addColor() {
    if (data.info.config.colors) {
      data.info.config.colors.push('');
    } else {
      data.info.config.colors = [''];
    }
    changeInfo();
  }
  function deleteColor() {
    data.info.config.colors.splice(-1);
    changeInfo();
  }
  function initChartColors() {
    if (!data.info.config.echarts.color) {
      data.info.config.echarts.color = [];
    }
    data.info.config.echarts.color = [];
    let colors = data.info.config.colors.filter((ele) => {
      return ele;
    });
    if (colors.length == 0) {
      // 默认颜色
      colors = [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4',
        '#ea7ccc',
      ];
    }
    for (let index = 0; index < colorLength.value.length; index++) {
      let colorIndex = index % colors.length;
      let color = colors[index] ? colors[index] : colors[colorIndex] ? colors[colorIndex] : '';
      data.info.config.echarts.color.push(color);
    }
  }
</script>

<style scoped>
  .color-box {
    margin-bottom: 20px;
  }
</style>
